let routes = require('./routes');
let userDao = require('../dao/userDao');
let playerDao = require('../dao/playerDao');
let sessionMgr = require('../core/sessionMgr');
let utils = require('../core/utils');
let Player = require('../module/player');

//用户登陆
routes.setNotLogin('userLogin', (msg, cb) => {
	let ret = utils.verification(msg, [
		['username', 'string']
	]);

	if (ret) {
		cb(102, ret);
		return;
	}
	let username = msg.username;
	userDao.findOne({
		username: username
	}, (res) => {
		if (res) {
			let userId = res._id;
			let session = sessionMgr.getByUid(userId);
			if (session) {
				sessionMgr.del(session.id);
			}
			session = sessionMgr.create(userId);
			cb(0, {
				username: res.username,
				sid: session.id
			});
			return;
		} else {
			cb(1);
		}
	});
}, {
	1: '用户不存在',
});


//用户注册
routes.setNotLogin('userRegister', (msg, cb) => {
	let ret = utils.verification(msg, [
		['username', 'string']
	]);

	if (ret) {
		cb(102, ret);
		return;
	}
	let username = msg.username;
	userDao.findOne({
		username: username
	}, (res) => {
		if (res) {
			cb(1);
			return;
		}
		userDao.newAndSave(username, username, (ret) => {
			cb(0);
		});
	});
}, {
	1: '用户名已存在',
});

//获取角色列表
routes.setUserLogin('getPlayerList', (session, msg, cb) => {
	let uId = session.uId;
	console.log(uId)
	playerDao.find({

	}, (res) => {
		console.log(res)
		cb(0, res);
	});
});

//角色登陆
routes.setUserLogin('selectPlayer', (session, msg, cb) => {
	let ret = utils.verification(msg, [
		['id', 'number']
	]);

	if (ret) {
		cb(102, ret);
		return;
	}

	let uId = session.uId;
	let id = msg.id;

	playerDao.findOne({
		uId: uId,
		_id: id
	}, (doc) => {
		if (doc) {
			let player = new Player(doc.player);
			sessionMgr.setPlayer(uId, player);
			cb(0, doc.player);
			return;
		}
		cb(1);
	});
}, {
	1: '角色id不存在',
});

//创建角色
routes.setUserLogin('createPlayer', (session, msg, cb) => {
	let ret = utils.verification(msg, [
		['name', 'string']
	]);
	if (ret) {
		cb(102, ret);
		return;
	}
	let uId = session.uId;
	let name = msg.name;
	playerDao.findOne({
		'player.name': name
	}, (doc) => {
		if (doc) {
			cb(1);
			return;
		}
		let player = new Player();
		player.name = name;
		playerDao.newAndSave(uId, player, (res) => {
			cb(0);
		});
	});
}, {
	1: '角色名已存在',
});